<?php

namespace app\common\validate;

use app\common\exception\OtherException;
use think\Validate;

class BaseValidate extends Validate
{
    public string $method = 'GET';

    public function post()
    {
        if(!$this->request->isPost()){
            throw new OtherException('请求方式错误');
        }
        $this->method = 'POST';
        return $this;
    }

    public function get()
    {
        if(!$this->request->isGet()){
            throw new OtherException('请求方式错误');
        }
        $this->method = 'GET';
        return $this;
    }

    public function put()
    {
        if(!$this->request->isPut()){
            throw new OtherException('请求方式错误');
        }
        $this->method = 'PUT';
        return $this;
    }

    public function delete()
    {
        if(!$this->request->isDelete()){
            throw new OtherException('请求方式错误');
        }
        $this->method = 'DELETE';
        return $this;
    }

    public function goCheck($scene = null, array $validateData = []): array
    {
        // 接收参数
        $params = [];
        switch ($this->method){
            case 'POST':
                $params = request()->post();
                break;
            case 'GET':
                $params = request()->param();
                break;
            case 'PUT':
                $params = request()->put();
                break;
            case 'DELETE':
                $params = request()->param();
//                var_dump($params);
                break;
        }

        // 合并验证参数
        $params = array_merge($params,$validateData);

        // 场景
        if($scene){
            $result = $this->scene($scene)->check($params);
        }else{
            $result = $this->check($params);
        }

        if(!$result){
            $exception = is_array($this->error) ? implode(';', $this->error) : $this->error;
            throw new OtherException($exception);
        }

        // 返回成功数据
        return $params;
    }
}